package com.example.validation.config;

import org.springframework.core.Ordered;
import org.springframework.core.annotation.Order;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.List;

@RestControllerAdvice
@Order(Ordered.LOWEST_PRECEDENCE - 1)
public class GlobalExceptionHandler {

    @ExceptionHandler(value = org.springframework.validation.BindException.class)
    public Object ConstraintViolationException(org.springframework.validation.BindException ex) {
        List<ObjectError> allErrors = ex.getBindingResult().getAllErrors();
        StringBuilder stringBuffer = new StringBuilder();
        for (ObjectError error : allErrors) {
            stringBuffer.append(error.getDefaultMessage()).append(",");
        }
        return stringBuffer.substring(0, stringBuffer.length() - 1);
    }

    @ExceptionHandler(Exception.class)
    public Object handleError(Exception e) {
        return e.getMessage();
    }

}
